//
//  YNMessagerReceiveHandle.h
//  Messenger
//
//  Created by iOS on 15/2/6.
//  Copyright (c) 2015年 孙浪. All rights reserved.
//
//  接收消息管理
//

#import "YNMessagerReceiveHandle.h"
#import "YNMessagerManager.h"
#import "YNMessage.h"
#import "SoundManager.h"
#import "YNMessagerReceiveHandle.h"
#import "YNRemindManager.h"
#import "RemindSet.h"
#import "PictureModel.h"
#import "AitContactManagerTool.h"
#import "XMPPFramework.h"
#import "YNMessageContactManager.h"
#import "YNRecentChatObejct.h"
#import "YNTwoPeopleChat.h"
#import "YNManyPeopleChat.h"
#import "YNContactManager.h"
#import "YNUser.h"
#import "YNBroadcastChat.h"
#import "YNBroadcastNotificationChat.h"
#import "YNIMmanager.h"
#import "YNIMTool.h"
#import "YNIMFrameworkMacro.h"
#import "YNSessionOpenfireManager.h"

#define kFlag_Read    0
#define kFlag_UnRead  1

#define kFaceHeight    21.0f

#define NotificationTime   3

@interface YNMessagerReceiveHandle ()
{
    NSString *userNo;
    YNMessagerManager *receiveMessage;
    RemindSet *remindSet;
    NSDate    *lastDate;
    BOOL      isPlayCueTone;   //是否播放提示音
}
@property(nonatomic,weak)id<YNXMPPprotocol> delegate;
@end

@implementation YNMessagerReceiveHandle

#pragma mark - cycle life
-(instancetype)initWith:(XMPPStream*)stream delegate:(id<YNXMPPprotocol>)delegate{
    self = [super init];
    if (self)
    {
        remindSet = [YNRemindManager queryMessageRemindSetting];
        lastDate = [NSDate date];
        self.delegate = delegate;
        receiveMessage = [[YNMessagerManager alloc]initWithDelegate:delegate];
        [receiveMessage addDelegate:self delegateQueue:dispatch_get_main_queue()];
        [receiveMessage activate:stream];
    }
    return self;
}

- (void)updateRemindSetting
{
    debugLog(@"声音设置改变");
    remindSet = nil;
    remindSet = [YNRemindManager queryMessageRemindSetting];
}

- (void)removeDelegate
{
    userNo = nil;
    [receiveMessage removeDelegate:self delegateQueue:dispatch_get_main_queue()];
    [receiveMessage deactivate];
    receiveMessage = nil;
}

#pragma mark - 发送消息
/// 发送文本消息
/// @param userId <#userId description#>
/// @param text <#text description#>
/// @param aitArray @数据
/// @param groupName <#groupName description#>
- (void)sendTextMessageToUserId:(NSString *)userId text:(NSString*)text aitArray:(NSString *)aitArray isTranspond:(BOOL)isTranspond groupName:(NSString*)groupName
{
    YNBubbleMessageChatType chatType = [YNMessagerReceiveHandle getCurrentMessageChatType:userId];
    YNMessage *message = [[YNMessage alloc] initWithText:text
                                                    toUserId:userId
                                                    chatType:chatType
                                                   groupName:groupName
                                                   mettingId:nil];
    message.aitContactMarkArray = aitArray;
    message.isTranspond = isTranspond;
    
    [receiveMessage sendMessage:message];
    [self saveMessageInDatabaseee:message];

    if(message.isTranspond == YES)
    {
        //增加转发时的通知
        [self addTranspondMessageNotification:message];
    }

}

/// 事先组装好message情况下发送消息
/// @param message <#message description#>
-(void)sendMessage:(YNMessage *)message{
    [receiveMessage sendMessage:message];
    [self saveMessageInDatabaseee:message];

    if(message.isTranspond == YES)
    {
        //增加转发时的通知
        [self addTranspondMessageNotification:message];
    }
}

/**HX** 发送普通消息回执 **/
-(void)sendReceiptMessageToUserId:(NSString*)userId type:(ReceiptMessageType)messageType{
    
    YNMessage *receiptMessage = [[YNMessage alloc] initWithReceiptMessageToUserId:userId];
    [receiveMessage sendReceiptMessage:receiptMessage type:messageType];
}

/**HX** 发送广播消息 **/
-(void)sendBroadcastMessage:(NSArray<NSString*>*)reciveUserIds body:(NSString*)body{
    [receiveMessage sendBroadcastMessage:reciveUserIds body:body];
}

//发送文件消息回执
- (void)sendFileReturnMessage:(YNMessage *)message
{
    [receiveMessage sendMessage:message];
    
}

/// 发送图片
/// @param message <#message description#>
/// @param pic <#pic description#>
/// @param block <#block description#>
- (void)sendPhotoMessage:(YNMessage *)message pic:(PictureModel *)pic uploadBlock:(uploadChatFileBlock)block
{
    //保存
    [self saveMessageInDatabaseee:message];
    
    debugLog(@"message.sendState=%ld",message.sendState);
    
    //2017-3-9jc修改，是转发，直接发送messenger消息。服务器上有图片。对方直接在服务器上获取图片就可以了。不用上传图片
    if(message.isTranspond== YES && message.sendState == YNMessageSendStateSuccess)
    {
        debugLog(@"转发图片");
        
        message.sendState = YNMessageSendStateSending;
        [self addTranspondMessageNotification:message];
        
        [receiveMessage sendMessage:message];
        
    }
    else
    {
        debugLog(@"发送图片");
        
        message.sendState = YNMessageSendStateSending;
        
        [self addTranspondMessageNotification:message];
        
        //上传图片到服务器
        [self postUploadImageWithMessage:message pic:pic uploadBlock:block];
    }
}

-(void)addTranspondMessageNotification:(YNMessage *)message
{
    if ([self.delegate respondsToSelector:@selector(transpondMessageNotification:)]) {
        [self.delegate transpondMessageNotification:message];
    }
}

//发送文件
- (void)sendFileMessage:(YNMessage *)message uploadBlock:(uploadChatFileBlock)block
{
    //保存
    [self saveMessageInDatabaseee:message];
    
    //转发
    if(message.isTranspond == YES  && message.sendState == YNMessageSendStateSuccess)
    {
        debugLog(@"转发的文件");
        
        message.sendState = YNMessageSendStateSending;
        [self addTranspondMessageNotification:message];
        
        [receiveMessage sendMessage:message];
    }
    //发送文件
    else
    {
        debugLog(@"发送文件");
        message.sendState = YNMessageSendStateSending;
        
        //上传文件到服务器
        [self postUploadFileWithMessage:message uploadBlock:block];
        
    }
    
    
}

//发送语音
- (void)sendVoiceMessage:(YNMessage *)message uploadBlock:(uploadChatFileBlock)block
{
    //保存
    [self saveMessageInDatabaseee:message];
    
    //上传语音
    [self postUploadVoiceWithMessage:message uploadBlock:block];
}

#pragma mark - 上传图片
- (void)postUploadImageWithMessage:(YNMessage *)message pic:(PictureModel *)pic uploadBlock:(uploadChatFileBlock)block
{
    //2017-2-24jc修改,可以上传原图
    NSURL *filePath ;
    if(message.isCompressImage==YES)
    {
        //2017-10-26jc添加，解决发送时，不一定是压缩图片还是群共享下载的图片文件
        if([YNIMTool isEmptyString:message.compressPath])
        {
            filePath = [NSURL fileURLWithPath:message.originPhotoUrl];
        }
        else
        {
            filePath = [NSURL fileURLWithPath:message.compressPath];
            debugLog(@"发送的是压缩图=%@",message.compressPath);
        }
    }
    else
    {
        NSString * imagePath = [message.originPhotoUrl copy];
        
        NSRange range = [imagePath rangeOfString:@"images/"];
        NSMutableString* compressImagePath=[[NSMutableString alloc]initWithString:imagePath];
        [compressImagePath insertString:@"compress"atIndex:range.location+7];
        
        UIImage * compressImage = [UIImage imageWithContentsOfFile:compressImagePath];
        
        if(compressImage)
        {
            filePath = [NSURL fileURLWithPath:compressImagePath];
            debugLog(@"发送的是压缩图=%@",compressImagePath);
        }
        else
        {
            
            filePath = [NSURL fileURLWithPath:message.originPhotoUrl];
            debugLog(@"发送的是原图=%@",message.originPhotoUrl);
        }
        
    }
    
    
    NSString *userType;
    if (message.chatType == YNBubbleMessageChatTypeWeChat)
    {
        userType = @"1";
    }
    else
    {
        userType = @"2";
    }
    
    NSString *imageName;
    if (pic)
    {
        imageName = pic.imageName;
    }
    else
    {
        imageName = [[message.originPhotoUrl componentsSeparatedByString:@"/"] lastObject];
        
        pic = [[PictureModel alloc]init];
        pic.key=message.packetId;
    }
    __block YNMessagerManager*blockReceiveMessage=receiveMessage;
    WEAKSELF
    if (block) {
        uploadChatFileResultBlock resultBlock = ^(BOOL success,NSString* fileId) {
            if (success) {
                NSDictionary*messageDic=[YNIMTool getJsonObjectFromJsonString:message.message];
                NSMutableDictionary*muDic = [NSMutableDictionary dictionaryWithDictionary:messageDic];
                [muDic setObject:[NSString stringWithFormat:@"<img key=\"%@\">", fileId] forKey:@"content"];
                NSArray*imagesArr = [messageDic objectForKey:@"images"];
                NSMutableArray*muImageArr = [NSMutableArray array];
                for (NSDictionary*objDic in imagesArr) {
                    NSMutableDictionary*muObjDic = [NSMutableDictionary dictionaryWithDictionary:objDic];
                    [muObjDic setObject:fileId forKey:@"fileId"];
                    [muObjDic setObject:fileId forKey:@"samllImageId"];
                    [muObjDic setObject:fileId forKey:@"key"];
                    [muImageArr addObject:muObjDic];
                }
                [muDic setObject:muImageArr forKey:@"images"];
                message.message = [YNIMTool jsonStringWithObject:muDic];
                [blockReceiveMessage sendMessage:message];
            }else{
                //发送失败
                message.sendState = YNMessageSendStateFailed;
                //更新数据库
                [YNMessageContactManager updateChatWithMessage:message changRecentChat:NO];
                
                //通知更新会话界面
                dispatch_async(dispatch_get_main_queue(), ^{
                    if ([weakSelf.delegate respondsToSelector:@selector(receiveMessageReceipt:)]) {
                        [weakSelf.delegate receiveMessageReceipt:message];
                    }
                });
            }
        };
        
        block(message.friendId,pic.key,userType,filePath,imageName,resultBlock);
    }
}

#pragma 上传文件
- (void)postUploadFileWithMessage:(YNMessage *)message uploadBlock:(uploadChatFileBlock)block
{
    NSURL *filePath = [NSURL fileURLWithPath:message.originPhotoUrl];
    NSString *userType;
    if (message.chatType == YNBubbleMessageChatTypeWeChat)
    {
        userType = @"1";
    }
    else
    {
        userType = @"2";
    }
    
    debugLog(@"fileId=%@,packetId=%@,userType=%@,filePath=%@,fileName=%@",message.friendId,message.packetId,userType,filePath,message.fileName);
    __block YNMessagerManager*blockReceiveMessage=receiveMessage;
    WEAKSELF
    if (block) {
        uploadChatFileResultBlock resultBlock = ^(BOOL success,NSString* fileId) {
            if (success) {
                NSDictionary*messageDic=[YNIMTool getJsonObjectFromJsonString:message.message];
                NSMutableDictionary*muDic = [NSMutableDictionary dictionaryWithDictionary:messageDic];
                [muDic setObject:[NSString stringWithFormat:@"<file key=\"%@\">", fileId] forKey:@"content"];
                NSArray*filesArr = [messageDic objectForKey:@"files"];
                NSMutableArray*muImageArr = [NSMutableArray array];
                for (NSDictionary*objDic in filesArr) {
                    NSMutableDictionary*muObjDic = [NSMutableDictionary dictionaryWithDictionary:objDic];
                    [muObjDic setObject:fileId forKey:@"fileId"];
                    [muObjDic setObject:fileId forKey:@"key"];
                    [muImageArr addObject:muObjDic];
                }
                [muDic setObject:muImageArr forKey:@"files"];
                message.message = [YNIMTool jsonStringWithObject:muDic];
                [blockReceiveMessage sendMessage:message];
            }else{
                //发送失败
                message.sendState = YNMessageSendStateFailed;

                if (message.messageMediaType == YNBubbleMessageFile)
                {
                    message.fileState = fileStateUploadFail;
                    [YNMessageContactManager updateMessageFileStateWithMessage:message];
                }

                //更新数据库
                [YNMessageContactManager updateChatWithMessage:message changRecentChat:NO];
                //通知更新会话界面
                dispatch_async(dispatch_get_main_queue(), ^{
                    if ([weakSelf.delegate respondsToSelector:@selector(receiveMessageReceipt:)]) {
                        [weakSelf.delegate receiveMessageReceipt:message];
                    }
                });
            }
        };
        
        block(message.friendId,message.packetId,userType,filePath,message.fileName,resultBlock);
    }
}

#pragma 上传语音
- (void)postUploadVoiceWithMessage:(YNMessage *)message uploadBlock:(uploadChatFileBlock)block
{
    NSString * voicePath = [message.voicePath copy];
    /**HX** 2018-01-23 注释掉，录音文件不来就是wav格式，读取存储的录音数据也是需要wav才能播放，而这里为什么要转为amr来上传呢，搞不懂 **/
//    voicePath = [voicePath stringByReplacingOccurrencesOfString:@"wav"withString:@"amr"];
    
    NSURL *urlVoicePath = [NSURL fileURLWithPath:voicePath];
    NSString *userType;
    if (message.chatType == YNBubbleMessageChatTypeWeChatVoice)
    {
        userType = @"1";
    }
    else
    {
        userType = @"2";
    }

    NSString * voiceId = [message.voiceId copy];
    voiceId = voiceId == nil ? @"" : [voiceId stringByAppendingString:@".mp3"];
    __block YNMessagerManager*blockReceiveMessage=receiveMessage;
    WEAKSELF
    if (block) {
        uploadChatFileResultBlock resultBlock = ^(BOOL success,NSString* fileId) {
            if (success) {
                NSDictionary*messageDic=[YNIMTool getJsonObjectFromJsonString:message.message];
                NSMutableDictionary*muDic = [NSMutableDictionary dictionaryWithDictionary:messageDic];
                NSDictionary*voiceDic=muDic[@"voice"];
                NSMutableDictionary*muVoiceDic = [NSMutableDictionary dictionaryWithDictionary:voiceDic];
                [muVoiceDic setObject:fileId forKey:@"id"];
                [muDic setObject:muVoiceDic forKey:@"voice"];
                message.message = [YNIMTool jsonStringWithObject:muDic];
                [blockReceiveMessage sendMessage:message];
            }else{
                //发送失败
                message.sendState = YNMessageSendStateFailed;
                if (message.messageMediaType == YNBubbleMessageFile)
                {
                    message.fileState = fileStateUploadFail;
                    [YNMessageContactManager updateMessageFileStateWithMessage:message];
                }
                //更新数据库
                [YNMessageContactManager updateChatWithMessage:message changRecentChat:NO];
                //通知更新会话界面
                dispatch_async(dispatch_get_main_queue(), ^{
                    if ([weakSelf.delegate respondsToSelector:@selector(receiveMessageReceipt:)]) {
                        [weakSelf.delegate receiveMessageReceipt:message];
                    }
                });
            }
        };
        
        block(message.friendId,message.voiceId,userType,urlVoicePath,voiceId,resultBlock);
    }
}

#pragma mark - 接收到回执的代理
- (void)receiveReceiptStateWithIQ:(XMPPIQ *)iq aMesssage:(YNMessage *)message
{
    if (iq)
    {
        //iq不为空，消息有回执，发送成功
        //更改状态
        message.sendState = YNMessageSendStateSuccess;
        
        //成功
        NSXMLElement *req = [iq elementForName:@"req"];
        NSString *sendTime = [[req elementForName:@"sendTime"] stringValue];
        
        message.sendTime = sendTime;
        
        if (message.messageMediaType == YNBubbleMessageFile)
        {
            message.fileState = fileStateUploaded;
            [YNMessageContactManager updateMessageFileStateWithMessage:message];
        }
 
        //更新数据库
        [self updateMessageOnDatabase:message];

        message.currentTime = [self dateStringFromMINDate:sendTime];
    }
    else
    {
        //发送失败
        message.sendState = YNMessageSendStateFailed;
        
        if (message.messageMediaType == YNBubbleMessageFile)
        {
            message.fileState = fileStateUploadFail;
            [YNMessageContactManager updateMessageFileStateWithMessage:message];
        }
        //更新数据库
        [self updateMessageOnDatabase:message];
    }
    //通知更新会话界面
    dispatch_async(dispatch_get_main_queue(), ^{
        if ([self.delegate respondsToSelector:@selector(receiveMessageReceipt:)]) {
            [self.delegate receiveMessageReceipt:message];
        }
        if ([self.delegate respondsToSelector:@selector(updataRecentChatInterface)]) {
            [self.delegate receiveChatMesWithRecentChatId:nil userNo:message.toUserId];
        }
    });
}

//更新消息到数据库
- (void)updateMessageOnDatabase:(YNMessage *)message
{
    [YNMessageContactManager updateChatWithMessage:message changRecentChat:NO];
}

//发送消息保存数据库
- (void)saveMessageInDatabaseee:(YNMessage *)message
{
    YNRecentChatObejct *recentChat = [[YNRecentChatObejct alloc] init];
    //保存最近会话到数据库
    recentChat.userNo = message.friendId;
    recentChat.chatType = message.chatType;
    recentChat.sendNo = message.fromUserId;
    recentChat.dataTime = message.sendTime;
    recentChat.topTime = nil;
    recentChat.headUrl = nil;
    recentChat.headLocalPath = nil;
    recentChat.isTop = kFlag_UnKnowTop;
    recentChat.unReadCount = 0;
    recentChat.sendState = YNMessageSendStateSending;
    recentChat.messageBody = message.message;
    recentChat.messageType = message.messageMediaType;
    recentChat.content = message.text;
    recentChat.masterRecentType=message.bubbleMessageType;
    recentChat.packId = message.packetId;
    //将消息分段转成数组, 然后再转成Json字符串保存数据库
    NSArray *messageArray = [self messageArrayConvertFromOldMessage:message.text messageBody:message.message];
    
    if (message.messageMediaType == YNBubbleMessageText)
    {
        if (messageArray.count)
        {
            NSData *jsonData = [NSJSONSerialization dataWithJSONObject:messageArray options:NSJSONWritingPrettyPrinted error:nil];
            message.text = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
        }
        else
        {
            message.text = [YNIMTool jsonStringWithObject:message.text];
        }
    }
    else if (message.messageMediaType == YNBubbleMessagePhoto)
    {
        NSData *jsonData = [NSJSONSerialization dataWithJSONObject:messageArray options:NSJSONWritingPrettyPrinted error:nil];
        message.text = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    }

    if (message.chatType == YNBubbleMessageChatTypeWeChat || message.chatType == YNBubbleMessageChatTypeWeChatVoice || message.chatType == YNBubbleMessageChatTypeFileWeChat)
    {
        //消息保存到数据库
        YNTwoPeopleChat *twoPeopleChat = [[YNTwoPeopleChat alloc] init];
        twoPeopleChat.packId = message.packetId;
        twoPeopleChat.chatUserNo = message.friendId;
        twoPeopleChat.fileId = nil;
        twoPeopleChat.messageType = message.messageMediaType;
        twoPeopleChat.isSendMsg = message.sendState;
        twoPeopleChat.message = message.text;
        twoPeopleChat.messageBody = message.message;
        twoPeopleChat.mTime = message.sendTime;
        twoPeopleChat.isReaded = message.isRead;
        twoPeopleChat.isSuccess = YNMessageSendStateSending;
        twoPeopleChat.masterType = message.bubbleMessageType;
        twoPeopleChat.content = message.body;
        twoPeopleChat.senderName = message.sender;
    
        if (message.messageMediaType == YNBubbleMessagePhoto)
        {
            twoPeopleChat.originPhotoUrl = message.originPhotoUrl;
            twoPeopleChat.fileName = message.fileName;
            recentChat.text = message.text;
        }
        else if (message.messageMediaType == YNBubbleMessageFile)
        {
            twoPeopleChat.fileState = message.fileState;
            twoPeopleChat.originPhotoUrl = message.originPhotoUrl;
            twoPeopleChat.fileName = message.fileName;
        }
        //2016-7-13jc添加
        else if(message.messageMediaType == YNBubbleMessageVoice)
        {
            twoPeopleChat.voiceState = message.voiceState;
            twoPeopleChat.voicePath= message.voicePath;
            twoPeopleChat.voiceId = message.voiceId;
            twoPeopleChat.voiceDuration= message.voiceDuration;
        }
        //2017-6-22jc添加，增加混合
        else if(message.messageMediaType == YNBubbleMessageMix)
        {
            twoPeopleChat.fileState =message.fileState;
            twoPeopleChat.fileName = message.fileName;
            twoPeopleChat.originPhotoUrl = message.originPhotoUrl;
            
        }
        
        [YNContactManager saveTwoPeopleChatWithMessage:twoPeopleChat];
        
        YNUser *user;
        
        if(message.chatType == YNBubbleMessageChatTypeWeChat || message.chatType == YNBubbleMessageChatTypeFileWeChat)
        {
            user= [YNContactManager queryUserNameByUserID:message.friendId chatType:YNBubbleMessageChatTypeWeChat];
        }
        else
        {
            user = [YNContactManager queryUserNameByUserID:message.friendId chatType:YNBubbleMessageChatTypeWeChatVoice];
        }
        
        
        recentChat.title = user.userName;
        recentChat.text = message.text;
    }
    
//    else if (message.chatType == YNBubbleMessageChatTypeGroupChat || message.chatType == YNBubbleMessageChatTypeDiscussion)
    
    else if (message.chatType == YNBubbleMessageChatTypeGroupChat || message.chatType == YNBubbleMessageChatTypeDiscussion || message.chatType == YNBubbleMessageChatTypeProjectTeamChat || message.chatType == YNBubbleMessageChatTypeGroupChatVoice ||  message.chatType == YNBubbleMessageChatTypeDiscussionVoice || message.chatType == YNBubbleMessageChatTypeProjectTeamVoice)
    {
        YNManyPeopleChat *manyPeopleChat = [[YNManyPeopleChat alloc] init];
        
        manyPeopleChat.packetId = message.packetId;
        manyPeopleChat.fromUserNo = message.fromUserId;
        manyPeopleChat.toUserNo = message.toUserId;
        manyPeopleChat.fileId = nil;
        manyPeopleChat.messageType = message.messageMediaType;
        manyPeopleChat.isSendMsg = message.sendState;
        manyPeopleChat.message = message.text;
        manyPeopleChat.messageBody = message.message;
        manyPeopleChat.mTime = message.sendTime;
        manyPeopleChat.isReaded = message.isRead;
        manyPeopleChat.isSuccess = YNMessageSendStateSending;
        manyPeopleChat.masterType = message.bubbleMessageType;
        manyPeopleChat.groupNo = message.friendId;
        manyPeopleChat.sendName = [YNIMmanager sharedInstance].userName;
        manyPeopleChat.content = message.body;
        manyPeopleChat.aitContactMark = 0;
        manyPeopleChat.aitContactMarkArray= message.aitContactMarkArray;
        
        if (message.messageMediaType == YNBubbleMessagePhoto)
        {
            manyPeopleChat.originPhotoUrl = message.originPhotoUrl;
            manyPeopleChat.fileName = message.fileName;
        }
        else if (message.messageMediaType == YNBubbleMessageFile)
        {
            manyPeopleChat.fileState = message.fileState;
            manyPeopleChat.originPhotoUrl = message.originPhotoUrl;
            manyPeopleChat.fileName = message.fileName;
        }
        //2016-7-13jc添加
        else if(message.messageMediaType == YNBubbleMessageVoice)
        {
            manyPeopleChat.voiceState = message.voiceState;
            manyPeopleChat.voicePath= message.voicePath;
            manyPeopleChat.voiceId = message.voiceId;
            manyPeopleChat.voiceDuration= message.voiceDuration;
        }
        
        //2017-6-22jc添加，增加混合
        else if(message.messageMediaType == YNBubbleMessageMix)
        {
            manyPeopleChat.fileState =message.fileState;
            manyPeopleChat.fileName = message.fileName;
            manyPeopleChat.originPhotoUrl = message.originPhotoUrl;
        }
        
        
//        if (message.chatType == YNBubbleMessageChatTypeGroupChat)
        if (message.chatType == YNBubbleMessageChatTypeGroupChat || message.chatType == YNBubbleMessageChatTypeGroupChatVoice )
        {
            [YNContactManager saverManyPeopleChatWithMesage:manyPeopleChat groupType:kContact_UserGroupType];
        }
        else if (message.chatType == YNBubbleMessageChatTypeDiscussion || message.chatType == YNBubbleMessageChatTypeDiscussionVoice)
        {
            [YNContactManager saverManyPeopleChatWithMesage:manyPeopleChat groupType:kContact_DiscussionGropType];
        }
        else//项目组
        {
            [YNContactManager saverManyPeopleChatWithMesage:manyPeopleChat groupType:kContact_ProjectTeamGropType];
        }
        recentChat.senderName = [YNIMmanager sharedInstance].userName;
        recentChat.title = message.groupName;
        recentChat.text = message.text;
    }
    else if (message.chatType == YNBubbleMessageChatTypeBroadcast)
    {
        
    }
    recentChat.senderName = @"我";
    [YNContactManager saveRecentChatWithMessage:recentChat isFromRoamingSource:NO];
    
    if ([self.delegate respondsToSelector:@selector(updataRecentChatInterface)]) {
        [self.delegate receiveChatMesWithRecentChatId:recentChat.packId userNo:recentChat.userNo];
    }
}



#pragma mark - YNMessagerManagerDelegate Methods

//设置铃音是否播放
- (void)updateSoundPlayTime
{
    NSDate *currentData = [NSDate date];
    NSTimeInterval timeInterval = [currentData timeIntervalSinceDate:lastDate];
    
    if (timeInterval > NotificationTime)
    {
        lastDate = currentData;
        isPlayCueTone = YES;
    }
    else if (timeInterval < 0)
    {
        lastDate = currentData;
        isPlayCueTone = YES;
    }
    else
    {
        isPlayCueTone = NO;
    }

}

//接受到两人消息
- (void)receiveMessageFromUser:(YNMessage *)message messageControType:(YNBubbleMessageType)controType
{
    //将消息保存到两人会话消息数据库
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        
        YNRecentChatObejct *recentChat = [YNMessagerReceiveHandle creatRecentChat:message];
        recentChat.title = recentChat.senderName;
        
        //将消息分段转成数组, 然后再转成Json字符串保存数据库
        NSArray *messageArray = [self messageArrayConvertFromOldMessage:message.text messageBody:message.message];
        
        //消息json化
//        if (messageArray.count)
        if (![YNIMTool isEmptyArray:messageArray] && messageArray.count>0)
        {
            NSData *jsonData = [NSJSONSerialization dataWithJSONObject:messageArray options:NSJSONWritingPrettyPrinted error:nil];
            message.text = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
            
            //判断是不是图文混排
            BOOL isPic = [[messageArray lastObject] boolValue];
            if (isPic)
            {
                //是就改变消息媒体类型
                NSUInteger imgCount = [[messageArray objectAtIndex:messageArray.count - 3] integerValue];
                if (imgCount)
                {
                    //是就改变消息媒体类型
                    message.messageMediaType = YNBubbleMessageMix;
                }
                else
                {
                    message.messageMediaType = YNBubbleMessageText;
                }
            }
        }
        else
        {
            message.text = [YNIMTool jsonStringWithObject:message.text];
        }
        
        recentChat.text = message.text;
        
        recentChat.messageType = message.messageMediaType;
        if ([self currentChatVC:message])
        {
            //-------------2016-8-1jc添加------------------------------------
            NSString * messageBody =[message.message copy];
            
            NSDictionary *msgDic = (NSDictionary*)[YNIMTool getJsonObjectFromJsonString:messageBody];
            
            NSString * msgType =[[msgDic objectForKey:@"msgType"] copy];
            
            
            NSInteger msgTypeInterger = [msgType integerValue];
            
            if(msgTypeInterger==15 || msgTypeInterger ==25 || msgTypeInterger == 35)
            {
                message.isRead = 0;
            }
            else
            {
                //在与User的聊天界面(人会话窗口打开)
                message.isRead = 1;
            }
            //-------------2016-8-1jc添加------------------------------------
            
            recentChat.unReadCount = kFlag_Read;
            [YNContactManager saveRecentChatWithMessage:recentChat isFromRoamingSource:NO];
            
            //在与用户聊天界面, 我们就计算好高度保存到数据库
            switch (message.messageMediaType) {
                case YNBubbleMessageMix:
                case YNBubbleMessageText:
                {
                    dispatch_async(dispatch_get_main_queue(), ^{
                        
                        if ([self.delegate respondsToSelector:@selector(receiveChatMessage:)]) {
                            [self.delegate receiveChatMessage:message];
                        }
                    });
                }
                    break;
                case YNBubbleMessagePhoto:
                {
                    dispatch_async(dispatch_get_main_queue(), ^{
                        
                        if ([self.delegate respondsToSelector:@selector(receiveChatMessage:)]) {
                            [self.delegate receiveChatMessage:message];
                        }
                    });
                }
                    break;
                case YNBubbleMessageFile:
                {
                    message.fileState = fileStateNotDownload;
                    debugLog(@"是文件消息");
                
                    dispatch_async(dispatch_get_main_queue(), ^{
                        
                        if ([self.delegate respondsToSelector:@selector(receiveChatMessage:)]) {
                            [self.delegate receiveChatMessage:message];
                        }
                    });
                }
                break;
                    
                    
                //2016-7-14jc添加
                case YNBubbleMessageVoice:
                {
                    message.voiceState = voiceStateNotDownload;
                    
                    debugLog(@"是语音消息");
                    
                    dispatch_async(dispatch_get_main_queue(), ^{
                        
                        if ([self.delegate respondsToSelector:@selector(receiveChatMessage:)]) {
                            [self.delegate receiveChatMessage:message];
                        }
                    });
                }
                    break;
                default:
                    break;
            }
        
        }
        else
        {
            //不在与user的聊天界面
            message.isRead = 0;
            if (controType==YNBubbleMessageTypeSending) {
                recentChat.unReadCount = kFlag_Read;
                [YNContactManager saveRecentChatWithMessage:recentChat isFromRoamingSource:NO];
            }else{
                recentChat.unReadCount = kFlag_UnRead;
                
                //发送提示音
                if (isPlayCueTone)
                {
                    //判断有没有开启免打扰功能
                    if (remindSet.isDistractionFree == 0)//没有开启免打扰
                    {
                        if (remindSet.isAudio == 1 && remindSet.isVibrate == 0)//如果只是声音提醒
                        {
                            debugLog(@"声音提醒");
                            
                            SoundManager *soundManager = [[SoundManager alloc] initMessageSoundEffectWithName:nil fileType:nil];
                            [soundManager play];
                            
                        }
                        else if (remindSet.isVibrate == 1 && remindSet.isAudio == 0)//如果只是震动提醒
                        {
                            debugLog(@"震动");
                            SoundManager *soundManager = [[SoundManager alloc] initMessageVibrate];
                            [soundManager play];
                        }
                        else if (remindSet.isVibrate == 1 && remindSet.isAudio == 1)//既有声音又有震动
                        {
                            SoundManager *soundManager = [[SoundManager alloc] initMessageSoundEffectWithName:nil fileType:nil];
                            [soundManager play];
                            
                        }
                    }
                    else //免打扰功能开启
                    {
                        //判断是否在免打扰时间内
                        BOOL isDistracFree = [self isBetweenStartTime:remindSet.DistractionFree_startTime endTime:remindSet.DistractionFree_endTime];
                        
                        if (!isDistracFree)//如果不在
                        {
                            //同上
                            if (remindSet.isAudio == 1 && remindSet.isVibrate == 0)
                            {
                                debugLog(@"声音提醒");
                                
                                SoundManager *soundManager = [[SoundManager alloc] initMessageSoundEffectWithName:nil fileType:nil];
                                [soundManager play];
                                
                            }
                            else if (remindSet.isVibrate == 1 && remindSet.isAudio == 0)
                            {
                                debugLog(@"震动");
                                SoundManager *soundManager = [[SoundManager alloc] initMessageVibrate];
                                [soundManager play];
                            }
                            else if (remindSet.isVibrate == 1 && remindSet.isAudio == 1)
                            {
                                SoundManager *soundManager = [[SoundManager alloc] initMessageSoundEffectWithName:nil fileType:nil];
                                [soundManager play];
                            }
                        }
                    }
                }
                [YNContactManager saveRecentChatWithMessage:recentChat isFromRoamingSource:NO];
            }
        }
        dispatch_async(dispatch_get_main_queue(), ^{
            if ([self.delegate respondsToSelector:@selector(updataRecentChatInterface)]) {
                [self.delegate receiveChatMesWithRecentChatId:recentChat.packId userNo:recentChat.userNo];
            }
        });
        
        //消息保存到数据库
        YNTwoPeopleChat *twoPeopleChat = [[YNTwoPeopleChat alloc] init];
        twoPeopleChat.packId = message.packetId;
        twoPeopleChat.chatUserNo = message.friendId;
        twoPeopleChat.fileId = nil;
        twoPeopleChat.messageType = message.messageMediaType;
        twoPeopleChat.isSendMsg = message.sendState;
        twoPeopleChat.message = message.text;
        twoPeopleChat.mTime = message.sendTime;
        twoPeopleChat.isReaded = message.isRead;
        twoPeopleChat.isSuccess = YNMessageSendStateSuccess;
        twoPeopleChat.masterType = message.bubbleMessageType;
        twoPeopleChat.messageBody = message.message;
        twoPeopleChat.content = message.body;
        twoPeopleChat.senderName = message.friendName;
        twoPeopleChat.fileState = fileStateNotDownload;
        
        [YNContactManager saveTwoPeopleChatWithMessage:twoPeopleChat];
    });
}

//接受到群组消息
- (void)receiveGroupMessage:(YNMessage *)message messageControType:(YNBubbleMessageType)controType
{
    if ([message.fromUserId isEqualToString:message.toUserId])
    {
        return;
    }
    else
    {
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            
            YNRecentChatObejct *recentChat = [YNMessagerReceiveHandle creatRecentChat:message];
            
            YNContactGroup *group = [YNContactManager queryUserNameByUserID:message.friendId chatType:message.chatType];
            recentChat.title = group.naturalName;
            
            //将消息分段转成数组, 然后再转成Json字符串保存数据库
            NSArray *messageArray = [self messageArrayConvertFromOldMessage:message.text messageBody:message.message];
            
            if (messageArray.count)
            {
                NSData *jsonData = [NSJSONSerialization dataWithJSONObject:messageArray options:NSJSONWritingPrettyPrinted error:nil];
                message.text = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
                
                //判断是不是图文混排
                BOOL isPic = [[messageArray lastObject] boolValue];
                if (isPic)
                {
                    //是就改变消息媒体类型
                    NSUInteger imgCount = [[messageArray objectAtIndex:messageArray.count - 3] integerValue];
                    if (imgCount)
                    {
                        //是就改变消息媒体类型
                        message.messageMediaType = YNBubbleMessageMix;
                    }
                    else
                    {
                        message.messageMediaType = YNBubbleMessageText;
                    }
                }
            }
            else
            {
                message.text = [YNIMTool jsonStringWithObject:message.text];
            }
            
            recentChat.text = message.text;
            
            recentChat.messageType = message.messageMediaType;
            if ([self currentChatVC:message])
            {
                //-------------2016-8-1jc添加------------------------------------
                NSString * messageBody =[message.message copy];
                
                NSDictionary *msgDic = (NSDictionary*)[YNIMTool getJsonObjectFromJsonString:messageBody];
                
                NSString * msgType =[[msgDic objectForKey:@"msgType"] copy];
                
                
                NSInteger msgTypeInterger = [msgType integerValue];
                
                if(msgTypeInterger==15 || msgTypeInterger ==25 || msgTypeInterger == 35)
                {
                    message.isRead = 0;
                }
                else
                {
                    //在与User的聊天界面(人会话窗口打开)
                    message.isRead = 1;
                }
                
                //-------------2016-8-1jc添加------------------------------------

                recentChat.unReadCount = kFlag_Read;
                [YNContactManager saveRecentChatWithMessage:recentChat isFromRoamingSource:NO];
                
                //在与用户聊天界面, 我们就计算好高度保存到数据库
                switch (message.messageMediaType) {
                    case YNBubbleMessageMix:
                    case YNBubbleMessageText:
                    {
                        dispatch_async(dispatch_get_main_queue(), ^{
                            if ([self.delegate respondsToSelector:@selector(receiveChatMessage:)]) {
                                [self.delegate receiveChatMessage:message];
                            }
                        });
                    }
                        break;
                    case YNBubbleMessagePhoto:
                    {
                        dispatch_async(dispatch_get_main_queue(), ^{
                            
                            if ([self.delegate respondsToSelector:@selector(receiveChatMessage:)]) {
                                [self.delegate receiveChatMessage:message];
                            }
                        });
                    }
                        break;
                    case YNBubbleMessageFile:
                    {
                        message.fileState = fileStateNotDownload;
                        dispatch_async(dispatch_get_main_queue(), ^{
                            
                            if ([self.delegate respondsToSelector:@selector(receiveChatMessage:)]) {
                                [self.delegate receiveChatMessage:message];
                            }
                        });
                    }
                        break;
                    //2016-7-14jc添加
                    case YNBubbleMessageVoice:
                    {
                        message.voiceState = voiceStateNotDownload;
                        dispatch_async(dispatch_get_main_queue(), ^{
                            
                            if ([self.delegate respondsToSelector:@selector(receiveChatMessage:)]) {
                                [self.delegate receiveChatMessage:message];
                            }
                        });
                    }
                        
                        break;
                    default:
                        break;
                }
            }
            else
            {
                message.isRead = 0;
                if (controType==YNBubbleMessageTypeSending) {
                    recentChat.unReadCount = kFlag_Read;
                    [YNContactManager saveRecentChatWithMessage:recentChat isFromRoamingSource:NO];
                }else{
                    recentChat.unReadCount = kFlag_UnRead;
                    
                    //播放声音
                    NSString *groupName = group.groupName;
                    if (isPlayCueTone)
                    {
                        if (remindSet.isDistractionFree == 0)//没有开启免打扰
                        {
                            if (remindSet.isAudio == 1 && remindSet.isVibrate != 1)//声音开启，震动关闭
                            {
                                [YNMessagerReceiveHandle setGroupRemindWithOpenSound:YES groupId:groupName];
                                
                            }
                            else if (remindSet.isVibrate == 1 && remindSet.isAudio != 1)//震动开启，声音关闭
                            {
                                [YNMessagerReceiveHandle setGroupRemindWithOpenSound:NO groupId:groupName];
                            }
                            else if (remindSet.isVibrate == 1 && remindSet.isAudio == 1)//震动、声音同时开启
                            {
                                [YNMessagerReceiveHandle setGroupRemindWithOpenSound:YES groupId:groupName];
                            }
                        }
                        else
                        {
                            BOOL isDistracFree = [self isBetweenStartTime:remindSet.DistractionFree_startTime endTime:remindSet.DistractionFree_endTime];
                            
                            if (!isDistracFree)
                            {
                                
                                if (remindSet.isAudio == 1 && remindSet.isVibrate != 1)//声音开启，震动关闭
                                {
                                    if (remindSet.isGroupAudio == 1)
                                    {
                                        [YNMessagerReceiveHandle setGroupRemindWithOpenSound:YES groupId:groupName];
                                    }
                                }
                                else if (remindSet.isVibrate == 1 && remindSet.isAudio != 1)//震动开启，声音关闭
                                {
                                    if (remindSet.isGroupVibrate == 1)
                                    {
                                        [YNMessagerReceiveHandle setGroupRemindWithOpenSound:NO groupId:groupName];
                                    }
                                    
                                }
                                else if (remindSet.isVibrate == 1 && remindSet.isAudio == 1)//震动、声音同时开启
                                {
                                    [YNMessagerReceiveHandle setGroupRemindWithOpenSound:YES groupId:groupName];
                                    
                                }
                            }
                        }
                    }
                    [YNContactManager saveRecentChatWithMessage:recentChat isFromRoamingSource:NO];
                }
            }
            
            dispatch_async(dispatch_get_main_queue(), ^{
                if ([self.delegate respondsToSelector:@selector(updataRecentChatInterface)]) {
                    [self.delegate receiveChatMesWithRecentChatId:recentChat.packId userNo:recentChat.userNo];
                }
            });
            
            YNManyPeopleChat *manyPeopleChat = [[YNManyPeopleChat alloc] init];
            manyPeopleChat.packetId = message.packetId;
            manyPeopleChat.fromUserNo = message.fromUserId;
            manyPeopleChat.toUserNo = message.toUserId;
            manyPeopleChat.fileId = nil;
            manyPeopleChat.messageType = message.messageMediaType;
            manyPeopleChat.isSendMsg = message.sendState;
            manyPeopleChat.message = message.text;
            manyPeopleChat.mTime = message.sendTime;
            manyPeopleChat.isReaded = message.isRead;
            manyPeopleChat.isSuccess = YNMessageSendStateSuccess;
            manyPeopleChat.groupNo = message.friendId;
            manyPeopleChat.masterType = message.bubbleMessageType;
            manyPeopleChat.sendName = recentChat.senderName;
            manyPeopleChat.messageBody = message.message;
            manyPeopleChat.content = message.body;
            manyPeopleChat.fileState = fileStateNotDownload;
            
            if (message.chatType == YNBubbleMessageChatTypeGroupChat || message.chatType == YNBubbleMessageChatTypeGroupChatVoice)
            {
                [AitContactManagerTool setAitContactMarkManyPeopleChat:manyPeopleChat groupType:kContact_UserGroupType];
                [YNContactManager saverManyPeopleChatWithMesage:manyPeopleChat groupType:kContact_UserGroupType];
            }
            else if (message.chatType == YNBubbleMessageChatTypeDiscussion || message.chatType == YNBubbleMessageChatTypeDiscussionVoice)
            {
                [AitContactManagerTool setAitContactMarkManyPeopleChat:manyPeopleChat groupType:kContact_DiscussionGropType];
                [YNContactManager saverManyPeopleChatWithMesage:manyPeopleChat groupType:kContact_DiscussionGropType];
            }else//项目组
            {
                [AitContactManagerTool setAitContactMarkManyPeopleChat:manyPeopleChat groupType:kContact_ProjectTeamGropType];
                [YNContactManager saverManyPeopleChatWithMesage:manyPeopleChat groupType:kContact_ProjectTeamGropType];
            }
        });
    }
}

+(void)setGroupRemindWithOpenSound:(BOOL)openSound groupId:(NSString*)groupId{
    NSInteger messRemind = [YNIMmanager queryMessageRemindWithGroupID:groupId];
    if (messRemind == 0) {
        return;
    }
    dispatch_async(dispatch_get_main_queue(), ^{
        if (openSound)//声音开启
        {
            debugLog(@"声音提醒");
            SoundManager *soundManager = [[SoundManager alloc] initMessageSoundEffectWithName:nil fileType:nil];
            [soundManager play];
        }
        else
        {
            debugLog(@"震动");
            SoundManager *soundManager = [[SoundManager alloc] initMessageVibrate];
            [soundManager play];
        }
    });
}

+(void)meetingReceiveMessage:(YNMessage *)message messageControType:(YNBubbleMessageType)controType{
    if (message.bubbleMessageType==YNBubbleMessageTypeSending)
    {
        return;
    }
    else
    {
        //将消息分段转成数组, 然后再转成Json字符串保存数据库
        NSArray *messageArray =[YNMessagerReceiveHandle parserMessageStr:message.text messageBody:message.message];
        if (messageArray.count)
        {
            NSData *jsonData = [NSJSONSerialization dataWithJSONObject:messageArray options:NSJSONWritingPrettyPrinted error:nil];
            message.text = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
            //判断是不是图文混排
            BOOL isPic = [[messageArray lastObject] boolValue];
            if (isPic)
            {
                //是就改变消息媒体类型
                NSUInteger imgCount = [[messageArray objectAtIndex:messageArray.count - 3] integerValue];
                if (imgCount)
                {
                    //是就改变消息媒体类型
                    message.messageMediaType = YNBubbleMessageMix;
                }
                else
                {
                    message.messageMediaType = YNBubbleMessageText;
                }
            }
        }
        else
        {
            message.text = [YNIMTool jsonStringWithObject:message.text];
        }
        message.isRead = 1;
        
        switch (message.messageMediaType) {
            case YNBubbleMessageMix:
            case YNBubbleMessageText:
            {
                dispatch_async(dispatch_get_main_queue(), ^{
                    
                    [[NSNotificationCenter defaultCenter] postNotificationName:kNotifacationLiveReceiveChatMessage object:message];
                });
            }
                break;
            case YNBubbleMessagePhoto:
            {
                dispatch_async(dispatch_get_main_queue(), ^{
                    
                    [[NSNotificationCenter defaultCenter] postNotificationName:kNotifacationLiveReceiveChatMessage object:message];
                });
                
            }
                break;
            case YNBubbleMessageFile:
            {
                message.fileState = fileStateNotDownload;
                dispatch_async(dispatch_get_main_queue(), ^{
                    [[NSNotificationCenter defaultCenter] postNotificationName:kNotifacationLiveReceiveChatMessage object:message];
                });
            }
                
                break;
            case YNBubbleMessageLive:
            {
                dispatch_async(dispatch_get_main_queue(), ^{
                    [[NSNotificationCenter defaultCenter] postNotificationName:kNotifacationLiveReceiveChatMessage object:message];
                });
            }
                break;
                //2016-7-14jc添加
            case YNBubbleMessageVoice:
            {
                message.voiceState = voiceStateNotDownload;
                
                dispatch_async(dispatch_get_main_queue(), ^{
                    
                    [[NSNotificationCenter defaultCenter] postNotificationName:kNotifacationLiveReceiveChatMessage object:message];
                });
            }
                break;
            default:
                break;
        }
    }
}
#pragma end

#pragma mark - manyCalculateMethod

//接受到广播消息
- (void)receiveBroadcastMessage:(YNMessage *)message
{
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
       
        YNRecentChatObejct *recentChat = [YNMessagerReceiveHandle creatRecentChat:message];
        recentChat.title = recentChat.senderName;
        recentChat.text = message.subject;
        message.isRead = 0;
        recentChat.unReadCount = kFlag_UnRead;
        [YNContactManager saveRecentChatWithMessage:recentChat isFromRoamingSource:NO];
        if ([self currentBroadcastVC])
        {
            dispatch_async(dispatch_get_main_queue(), ^{
                if ([self.delegate respondsToSelector:@selector(receiveBroadcastUpdataInterface:)]) {
                    [self.delegate receiveBroadcastUpdataInterface:message];
                }
            });
        }
        else
        {
            //发送提示音
            if (isPlayCueTone)
            {
                //判断有没有开启免打扰功能
                if (remindSet.isDistractionFree == 0)//没有开启免打扰
                {
                    if (remindSet.isAudio == 1 && remindSet.isVibrate == 0)//如果只是声音提醒
                    {
                        debugLog(@"声音提醒");
                        
                        SoundManager *soundManager = [[SoundManager alloc] initMessageSoundEffectWithName:nil fileType:nil];
                        [soundManager play];
                        
                    }
                    else if (remindSet.isVibrate == 1 && remindSet.isAudio == 0)//如果只是震动提醒
                    {
                        debugLog(@"震动");
                        SoundManager *soundManager = [[SoundManager alloc] initMessageVibrate];
                        [soundManager play];
                    }
                    else if (remindSet.isVibrate == 1 && remindSet.isAudio == 1)//既有声音又有震动
                    {
                        SoundManager *soundManager = [[SoundManager alloc] initMessageSoundEffectWithName:nil fileType:nil];
                        [soundManager play];
                        
                    }
                }
                else //免打扰功能开启
                {
                    //判断是否在免打扰时间内
                    BOOL isDistracFree = [self isBetweenStartTime:remindSet.DistractionFree_startTime endTime:remindSet.DistractionFree_endTime];
                    
                    if (!isDistracFree)//如果不在
                    {
                        //同上
                        if (remindSet.isAudio == 1 && remindSet.isVibrate == 0)
                        {
                            debugLog(@"声音提醒");
                            
                            SoundManager *soundManager = [[SoundManager alloc] initMessageSoundEffectWithName:nil fileType:nil];
                            [soundManager play];
                            
                        }
                        else if (remindSet.isVibrate == 1 && remindSet.isAudio == 0)
                        {
                            debugLog(@"震动");
                            SoundManager *soundManager = [[SoundManager alloc] initMessageVibrate];
                            [soundManager play];
                        }
                        else if (remindSet.isVibrate == 1 && remindSet.isAudio == 1)
                        {
                            SoundManager *soundManager = [[SoundManager alloc] initMessageSoundEffectWithName:nil fileType:nil];
                            [soundManager play];
                        }
                    }
                }
            }
        }
        dispatch_async(dispatch_get_main_queue(), ^{
            if ([self.delegate respondsToSelector:@selector(updataRecentChatInterface)]) {
                [self.delegate updataRecentChatInterface];
            }
        });
        
        //广播消息保存到数据库
        YNBroadcastChat *broadcast = [[YNBroadcastChat alloc] init];
        broadcast.packetId = message.packetId;
        broadcast.subject = message.subject;
        broadcast.fromUserNo = message.fromUserId;
        broadcast.toUserNo = message.toUserId;
        broadcast.messageType = 0;
//        broadcast.message = message.text;
        /**HX** 添加广播附件时的修改 **/
        broadcast.message=message.message;
        broadcast.mTime = message.sendTime;
        broadcast.senderName = @"";
        NSDictionary*messageDic=(NSDictionary*)[YNIMTool getJsonObjectFromJsonString:message.message];
        if (![YNIMTool isEmptyObject:messageDic[@"sendName"]]) {
            broadcast.senderName=messageDic[@"sendName"];
        }
        broadcast.recipient = nil;
        broadcast.headerUrl = message.avatarUrl;
        broadcast.isRead=NO;
        [[YNIMmanager sharedInstance]addBroadcastUnreadMsgIds:broadcast.packetId];
        [YNMessageContactManager saveBroadcastWithMessage:broadcast];
    });
}

//接受到系统通知消息
- (void)receiveSystemNotificationMessage:(YNMessage *)message
{
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        message.isRead = 0;
        YNBroadcastNotificationChat *broadcastNotification = [[YNBroadcastNotificationChat alloc] init];
        broadcastNotification.packetId = [XMPPStream generateUUID];
        broadcastNotification.subject = message.subject;
        broadcastNotification.fromUserNo = message.fromUserId;
        broadcastNotification.toUserNo = message.toUserId;
        broadcastNotification.content = message.text;
        broadcastNotification.link = @"";
        broadcastNotification.mTime = message.sendTime;
        broadcastNotification.senderName = message.friendName;
        broadcastNotification.recipient = nil;
        broadcastNotification.broadcastNotificationType = message.broadcastNotificationType;
        broadcastNotification.sourceTerminal = message.sourceTerminal;
        broadcastNotification.isRead = message.isRead;
    
        [YNMessageContactManager saveBroadcastNotificationWithMessage:broadcastNotification];
        
//        dispatch_async(dispatch_get_main_queue(), ^{
//            //更新事件界面
//        });
    });
}

#pragma  end

#pragma maek - 重新发送消息

- (void)reSendMessage:(YNMessage *)message uploadBlock:(uploadChatFileBlock)block
{
    switch (message.messageMediaType) {
        case YNBubbleMessagePhoto:
            
            [self postUploadImageWithMessage:message pic:nil uploadBlock:block];
            
            break;
        case YNBubbleMessageFile:
            [self postUploadFileWithMessage:message uploadBlock:block];
            break;
        case YNBubbleMessageVoice:
            [self postUploadVoiceWithMessage:message uploadBlock:block];
            break;
        default:
            [receiveMessage sendMessage:message];
            break;
    }
}

#pragma end
//判断当前是否是好友聊天界面
- (BOOL)currentChatVC:(YNMessage *)message
{
    userNo = nil;
    userNo = [[YNIMmanager sharedInstance] getIdCurrChatWithUser];
    if ([userNo isEqualToString:message.friendId])
    {
        return YES;
    }
    return NO;
}

- (BOOL)currentBroadcastVC
{
    userNo = nil;
    userNo = [[YNIMmanager sharedInstance]getIdCurrBroadcastView];
    if (userNo != nil) {
        return YES;
    }
    return NO;
}

//创建RecentChat对象
+ (YNRecentChatObejct *)creatRecentChat:(YNMessage *)msg
{
    YNRecentChatObejct *recentChat = [[YNRecentChatObejct alloc] init];
    
    if (msg.chatType == YNBubbleMessageChatTypeBroadcast)
    {
        recentChat.userNo = @"广播";
        recentChat.content = msg.subject;
        recentChat.chatType = msg.chatType;
        recentChat.sendNo = msg.fromUserId;
        recentChat.dataTime = msg.sendTime;
        recentChat.topTime = nil;
        recentChat.headUrl = nil;
        recentChat.headLocalPath = nil;
        recentChat.messageBody = msg.message;
        recentChat.senderName = @"广播";
        recentChat.isTop = kFlag_UnKnowTop;
        recentChat.sendState = YNMessageSendStateSuccess;
        return recentChat;
    }
    
    recentChat.userNo = msg.friendId;
    recentChat.content = msg.body;
    recentChat.chatType = msg.chatType;
    recentChat.sendNo = msg.fromUserId;
    recentChat.dataTime = msg.sendTime;
    recentChat.topTime = nil;
    recentChat.headUrl = nil;
    recentChat.headLocalPath = nil;
    recentChat.messageBody = msg.message;
    recentChat.isMessageWithdraw=msg.isMessageWithdraw;
    recentChat.senderName = msg.friendName;
    recentChat.isTop = kFlag_UnKnowTop;
    recentChat.sendState = YNMessageSendStateSuccess;
    recentChat.masterRecentType=msg.bubbleMessageType;
    recentChat.packId = msg.packetId;
    
    return recentChat;
}

//获取发送时间
- (NSString *)dateStringFromMINDate:(NSString *)time
{
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss.SSS"];
    if (time)
    {
        NSDate *date = [dateFormatter dateFromString:time];
        if (date == nil)
        {
            [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
            date = [dateFormatter dateFromString:time];
        }
        [dateFormatter setDateFormat:@"HH:mm"];
        NSString *serverTime = [dateFormatter stringFromDate:date];
        return serverTime;
    }
    else
    {
        NSString *localityTime = [dateFormatter stringFromDate:[NSDate date]];
        return localityTime;
    }
}

#pragma end

#pragma mark - parserMessageMethod
//将消息解析
- (NSArray *)messageArrayConvertFromOldMessage:(NSString *)oldMessage messageBody:(NSString *)messageBody;
{
    NSArray *array = [YNMessagerReceiveHandle parserMessageStr:oldMessage messageBody:messageBody];
    
    return array;
}

//判断是否在免打扰时间内
- (BOOL)isBetweenStartTime:(NSString *)startTime endTime:(NSString *)endTime
{
    NSDate *startDate = [self getCustomDateWithTime:startTime];
    NSDate *endDate = [self getCustomDateWithTime:endTime];
    
    //当前时间
    NSDate *currentDate = [NSDate date];
    
    if ([startDate compare:endDate] == NSOrderedAscending)
    {
        if ([currentDate compare:startDate] == NSOrderedDescending && [currentDate compare:endDate] == NSOrderedAscending)
        {
            //NSLog(@"1当前时间：%@ 在 %@-%@ 之间！",currentDate, endDate, startDate);
            return YES;
        }
        
        return NO;
    }
    else
    {
    
        if ([currentDate compare:endDate]== NSOrderedDescending && [currentDate compare:startDate] == NSOrderedAscending)
        {
            //NSLog(@"2当前时间：%@在 %@-%@ 之间！",currentDate, startDate, endDate);
            return NO;
        }
        
        return YES;
    
    }
}

/**
 * @brief 生成当天的某个点（返回的是伦敦时间，可直接与当前时间[NSDate date]比较）
 * @param theTime 如08:00
 */
- (NSDate *)getCustomDateWithTime:(NSString *)theTime
{
    //获取当前时间
    NSArray *timeArray = [theTime componentsSeparatedByString:@":"];
    NSDate *currentDate = [NSDate date];
    NSCalendar *currentCalendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
    
    NSInteger unitFlags = NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit | NSWeekdayCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit;
    
    NSDateComponents *currentComps = [currentCalendar components:unitFlags fromDate:currentDate];

    //设置当天的某个点
    NSDateComponents *resultComps = [[NSDateComponents alloc] init];
    [resultComps setYear:[currentComps year]];
    [resultComps setMonth:[currentComps month]];
    [resultComps setDay:[currentComps day]];
    [resultComps setHour:[[timeArray firstObject] integerValue]];
    [resultComps setMinute:[[timeArray lastObject] integerValue]];
    NSCalendar *resultCalendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
    
    return [resultCalendar dateFromComponents:resultComps];
}
#pragma end

/**
 *  返回一个数组
 *  可能为空数组
 *  或者 是 [字符串|图片|表情 ... , 表情个数, 是否图片文本混排]
 */
+ (NSMutableArray*)parserMessageStr:(NSString *)message messageBody:(NSString *)messageBody
{
    NSError *error = NULL;
    
    NSDictionary *msgDic = (NSDictionary*)[YNIMTool getJsonObjectFromJsonString:messageBody];

    NSMutableArray *tempArray = [NSMutableArray array];

    NSArray *images = [msgDic objectForKey:@"images"];
    
    NSRegularExpression *regex = [[NSRegularExpression alloc] initWithPattern:@"\\[/([0-9]|[1-7][0-9]|[1][0-2][0-9][0-9]|80)\\]|\\<img key=\"(.*?)\"\\>" options:NSRegularExpressionUseUnicodeWordBoundaries error:&error];
    
    //匹配
    if ([YNIMTool isEmptyString:message]) {
        message=@"";
    }
    NSArray *chunks = [regex matchesInString:message options:0 range:NSMakeRange(0, [message length])];
    
    
    if (chunks.count > 0)
    {
        NSInteger index = 0;       //零时尾部坐标
        NSString *strValue = @"";  //str
        NSUInteger faceCount = 0;  //表情个数
        NSUInteger imgCount = 0; //图片个数
        
        //遍历匹配出来的资源
        for (NSTextCheckingResult *b in chunks)
        {
            NSInteger location = b.range.location;
            NSInteger length = b.range.length;
 
            //将资源之前的字符串添加到数组
            if (location > index)
            {
                strValue = [message substringWithRange:NSMakeRange(index, location - index)];
                [tempArray addObject:strValue];
            }
            
            //获取当前适配字符串末尾坐标
            index = location + length;
            
            //判断是不是表情
            NSRange faceRang = [b rangeAtIndex:1];
            NSMutableDictionary *dic = [NSMutableDictionary dictionary];
            if (faceRang.length)
            {
                //是表情, 获取表情的值
                NSString *faceStr = [message substringWithRange:[b rangeAtIndex:1]];
                [dic setObject:faceStr forKey:@"face"];
                faceCount += 1;
                
                //将资源保存到数组
                [tempArray addObject:dic];
            }
            else
            {
                //是图片, 获取图片的ID
                NSString *imgStr = [message substringWithRange:[b rangeAtIndex:2]];
                
                [dic setObject:imgStr forKey:@"key"];
                NSDictionary *imgInfo = [self imageInfoWithImageKey:imgStr images:images];
                //判断是不是图片
                
                if (imgInfo)
                {
                    [dic setObject:imgStr forKey:@"img"];
                    
                    NSString *type = [[[imgInfo objectForKey:@"name"] componentsSeparatedByString:@"."] lastObject];
                    
                    NSString *imageName = [NSString stringWithFormat:@"%@.%@", imgStr, type];
                    
                    [dic setObject:imageName forKey:@"name"];
                    
                    imgCount += 1;
                    
                    //将资源保存到数组
                    [tempArray addObject:dic];
                }
                else
                {
                    //说明不是图片, 只是和图片相识的字符串
                    [tempArray addObject:imgStr];
                }
            }
        }
        
        //如果末尾还有字符串, 添加到数组
        if ([message length] > index)
        {
            strValue = [message substringFromIndex:index];
            [tempArray addObject:strValue];
        }
        [tempArray addObject:[NSNumber numberWithInteger:imgCount]];
        
        //添加表情个数到数组
        [tempArray addObject:[NSNumber numberWithInteger:faceCount]];
        
        //判断有没有字符串
        if (strValue.length || faceCount)
        {
            //图文混排或几张图片
            [tempArray addObject:[NSNumber numberWithBool:YES]];
        }
        else
        {
            if (imgCount > 0)
            {
                if (imgCount == 1)
                {
                    //单独1张图片
                    [tempArray addObject:[NSNumber numberWithBool:NO]];
                }
                else
                {
                    //多张图片
                    [tempArray addObject:[NSNumber numberWithBool:YES]];
                }
            }
        }
    }
    return tempArray;
}

+ (NSDictionary *)imageInfoWithImageKey:(NSString *)key images:(NSArray *)images
{
    NSDictionary *imgDic;
    
    for (NSDictionary *imgInfo in images)
    {
        NSString *fileId = [imgInfo objectForKey:@"fileId"];
        if ([fileId isEqualToString:key])
        {
            imgDic = [NSDictionary dictionaryWithDictionary:imgInfo];
            break;
        }
    }
    return imgDic;
}
/**
 判断群，讨论组，项目组，两人会话
 
 @param userNo
 @return 0：二人会话 1:群 2：讨论组 3：项目组
 */
+(CurrenChatObjType)getCurrentMessageChatTypemanyPeopleChatWith:(NSString *)userNo
{
    CurrenChatObjType chatType ;
    if ([userNo rangeOfString:DiscussionGroupFlag].length > 0)
    {
        chatType = CurrenChatObjType_discussion;
    }
    else if ([userNo rangeOfString:UserGroupFlag].length > 0)
    {
        chatType = CurrenChatObjType_group;
    }
    else if([userNo rangeOfString:ProjectTeamFlag].length > 0)
    {
        chatType = CurrenChatObjType_projectTeam;
    }
    else
    {
        chatType = CurrenChatObjType_twoPeople;
    }
    
    return chatType;
    
}
+ (YNBubbleMessageChatType)getCurrentMessageChatType:(NSString*)msgId
{
    YNBubbleMessageChatType chatType;
    if ([msgId rangeOfString:DiscussionGroupFlag].length > 0)
    {
        chatType = YNBubbleMessageChatTypeDiscussion;
    }
    else if ([msgId rangeOfString:UserGroupFlag].length > 0)
    {
        chatType = YNBubbleMessageChatTypeGroupChat;
    }
    else if ([msgId rangeOfString:ProjectTeamFlag].length > 0)
    {
        chatType = YNBubbleMessageChatTypeProjectTeamChat;
    }
    else
    {
        chatType = YNBubbleMessageChatTypeWeChat;
    }
    return chatType;
}
@end
